package service;

import model.Video;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import dao.VideoDao;
import util.DatabaseUtil;

public class VideoService {
    private final List<Video> videos = new ArrayList<>();
    private final static VideoService instance = new VideoService();
    private final VideoDao videoDao = new VideoDao();

    private VideoService() {
        // 初始化一些测试数据
        videos.add(new Video("1", "示例视频1", "/videos/sample1.mp4"));
        videos.add(new Video("2", "示例视频2", "/videos/sample2.mp4"));
    }

    public static VideoService getInstance() {
        return instance;
    }

    public List<Video> getAllVideos() {
        List<Video> videos = new ArrayList<>();
        String sql = "SELECT * FROM videos ORDER BY upload_time DESC";

        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                Video video = new Video(
                        rs.getString("id"),
                        rs.getString("title"),
                        rs.getString("file_path")
                );
                videos.add(video);
            }
        } catch (SQLException e) {
            System.err.println("查询视频列表失败: " + e.getMessage());
        }
        return videos;
    }

    public Video getVideoById(String id) {
        for (Video video : videos) {
            if (video.getId().equals(id)) {
                video.incrementViewCount();
                return video;
            }
        }
        return null;
    }



    public boolean addVideo(Video video) {
        // 最终验证
        if (video.getFilePath() == null || video.getFilePath().trim().isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }

        String sql = "INSERT INTO videos (title, file_path) VALUES (?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setString(1, video.getTitle());
            stmt.setString(2, video.getFilePath());

            int affectedRows = stmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = stmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        video.setId(rs.getString(1)); // 获取自增ID
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            System.err.println("数据库错误详情:");
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteVideo(String id) {
        return videos.removeIf(v -> v.getId().equals(id));
    }

}
